// AdiOSServer.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "User\ClientConnection.h"
#include "FileSystem\FileSystem.h"

SOCKET InitNetwork(const int portnumber)
{
	WSADATA wsd;		// winsock dll info
	SOCKADDR_IN info;	// server info
	int result;
	SOCKET sock=0;

	try
	{
		// Load Winsock Dll
		result = WSAStartup(MAKEWORD(2,2),&wsd);
		if(result){throw("[CNetProcessor::InitNetwork]: Unable to initiate WS2_32.DLL");}

		// Create Listening Socket
		sock = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
		if(sock == INVALID_SOCKET){throw("[CNetProcessor::InitNetwork]: Unable to construct listening socket");}
		
		// set server info then bind
		info.sin_family = AF_INET;
		info.sin_addr.s_addr = INADDR_ANY;
		info.sin_port = htons(portnumber);
		result = bind(sock,(sockaddr*)&info,sizeof(struct sockaddr));

		// Start socket listening - max of 50 connections waiting in backlog before rejected
		result = listen(sock,50);			
		if(result){throw("[CNetProcessor::InitNetwork]: Unable to get socket listening");}
		
	}
	catch(const char* error)
	{
		cout<<WSAGetLastError()<<" : "<<error<<endl;
		WSACleanup();

		return 0;
	}
	return sock;
}

// Check For New Connections
SOCKET CheckConnection(SOCKET sock)
{
	fd_set conn;
	int s;					// amount of sockets that need tending to
	int size = sizeof(sockaddr_in);

	// set time out to 0 so its non-blocking
	timeval time;	
	time.tv_sec = time.tv_usec = 0;
	
	// clear socket set so if anything is in it then there is a connection
	FD_ZERO(&conn);			// clear socket set
	FD_SET(sock,&conn);

	s = select(0,&conn,NULL,NULL,&time);

	if( s > 0)
	{
			SOCKET u_sock = accept(sock,NULL,NULL);
			if (u_sock)
			{
				return u_sock;
			}
	}

	return 0;
}

int _tmain(int argc, _TCHAR* argv[])
{
	cout<<PRODUCT_NAME<<" started version "<<PRODUCT_VERSION<<endl;
	if(!sysRoot){sysRoot = new CSysRoot();}

	SOCKET listeningSocket = InitNetwork(PRODUCT_PORT);
	if(!listeningSocket){cout<<"TCP ERROR: Failed to open port "<<PRODUCT_PORT<<", permissions error or port was already in use, product will now exit"<<endl; return 0;}

	/* the main thread now needs do nothing than listen for connections and then handle them */
	while(true)
	{
		SOCKET newSock = CheckConnection(listeningSocket);
		if(newSock)
		{
			/* connection made, spawn a listening thread to handle it */
			CClientConnection* t = new CClientConnection(newSock);
		}
		Sleep(10);
	}
	return 0;
}

